# import time
# import camera
# from machine import Pin
# import sim
# from usr import led
# from usr import simNet

import fota
import audio
import uos
import ubinascii
import request
import ujson
import ure
import utime
import camera
import log
from uio import StringIO
from machine import Pin
import _thread
from queue import Queue
from misc import Power
import uwebsocket
# from uartx import *
import usocket
import ussl
import queue
from machine import UART    


PROJECT_NAME = "DaoMangTu"
PROJECT_VERSION = "1.0.0"

log.basicConfig(level=log.INFO)
fota_log = log.getLogger("Fota")
log.basicConfig(level=log.INFO)
sse_log = log.getLogger("SSE")

q = Queue()



log.basicConfig(level=log.INFO)
TOKEN = ""
time_log = log.getLogger("LocalTime")
cam = camera.camCapture(0,640,480,2,0,0)
def cb(result_list):
    print("\nReceived result:", result_list[0])
    print("\nReceived result:",result_list[1])
    pass
print(cam.callback(cb))
if cam.open() != 0:
    print(cam.close())
    print(cam.open())

aud = audio.Audio(0)
aud.setVolume(10)
tts = audio.TTS(0)

tts.play(1, 0, 2, '导盲兔为您看见')
t1 = utime.mktime(utime.localtime())
Token_get = request.get(
    "https://web.daomangtu.com/jeecgboot/tbldevicecode/deviceCodeGenerator/generateDeviceToken?deviceId=123456789",
    sizeof=4096
)
t_str = Token_get.json()
if "message" in t_str:
    TOKEN = t_str["message"]
    t2 = utime.mktime(utime.localtime())
    # tts.play(1, 0, 2, TOKEN)
    print("Token:", TOKEN)
else:
    print("Error: Token not found in response")
    TOKEN = ""
print(t1,t2)


uart2 = ""
json_data_uart = ""
data_json = queue.Queue()
# def uart_cb(result_list):
#     rece_len = result_list[2]
#     if rece_len <= 0:
#         print("received data:null")
#         return
#     json_data_uart = uart2.read(uart2.any()).decode()
#     data_json.put(json_data_uart)
def uart_cb():
    while True:
        if uart2.any() <= 0:
            continue
        json_data_uart = uart2.read(uart2.any()).decode()
        data_json.put(json_data_uart)

_thread.start_new_thread(uart_cb,())
        # client.send(data)
        # print(data)
        # print("Sent", current_chunk," bytes, remaining:", remaining)
    # while(len(json_data_uart)):
    #     chunk_size = min(1024, len(json_data_uart))
    #     chunk = json_data_uart[:chunk_size]
    #     client.send(chunk)
    #     json_data_uart = json_data_uart[chunk_size:]
    #     print("Sent", chunk_size," bytes, remaining:", len(json_data_uart),"data:",chunk)
    #print("All data sent.")

def uart_send():
    while True:
        json_data_uart = data_json.get()
        if not json_data_uart:
            continue
        while len(json_data_uart):
            chunk_size = min(1024*7, len(json_data_uart))
            chunk = json_data_uart[:chunk_size]
            client.send(chunk)
            json_data_uart = json_data_uart[chunk_size:]
            print("Sent", chunk_size," bytes, remaining:", len(json_data_uart),"data:",chunk[-3:])
_thread.start_new_thread(uart_send,())

uart2 = UART(UART.UART2,921600,8,0,1,0)
# uart2.set_callback(uart_cb)

url = "wss://web.daomangtu.com/jeecgboot/DaoMangTuWebSocket/123456789?token="+TOKEN

def recv(cli):
    while True:
        # 死循环接收数据
        recv_data = cli.recv()
        #print("recv_data_cli: ",recv_data)
        if type(recv_data) == bytes:
             aud.playStream(1,recv_data)
        if not recv_data:
            print("cli close")
            client.close()
            break

client = uwebsocket.Client.connect(url, debug=False)
_thread.start_new_thread(recv, (client,))
#client.send("{\"msgType\":\"8\",\"text\":\"韩立看着厉飞雨渐渐远去的背影，静静地站在原地，沉默不语。刚才约好了第二天中午前来拿药后，他就主动的向韩立辞别了，说是要回去再调养一番。这么长的时间里，韩立一直都没有追问厉飞雨服用这种秘药的原因。韩立知道，就算问了也改变不了已发生的事情。既然他宁肯不要自己将来的一切，只愿意换取风光荣耀的“厉师兄”现在，说明他肯定有自己不得不这样做的苦衷。没有人会自愿自杀，即使是慢性的有高昂代价的自杀也没有人会心甘情愿的去这么做。如果非要他把苦衷说出来，只会让他把已快愈合的伤疤再血淋淋的揭开一次。很明显，韩立这样做是对的。在临走前，厉飞雨见他并没有追问自己服用“抽髓丸”的具体原因，很是为他的善解人意而感激，嘴上虽然没说，但韩立知道对方又欠了自己一个不大不小的人情。韩立准备遵守和他的约定，不但不会把他的秘密外传，还决定一回到山谷就为他配制能减轻痛苦的秘药。会这么做的原因很简单，既然对方不是个小人，没有对自己真的下杀手，那么自己就要让对方欠下自己一个更大的人情，让他不好拒绝自己以后提出的要求。厉飞雨的武功在最后几年里只会越来越高，对方的武功越高，对自己有帮助的可能性就越大。就算在今后几年里不需要他的帮忙，这也无所谓。轻轻地帮一下一个不算是坏人的人，对自己也算是一件让身心愉快的事情。虽然厉飞雨不见得就一定是个好人，但起码经历过今天这件事，他对自己是不会有什么危害了。韩立在把所有一切前前后后的想了一遍，觉得并没有什么遗漏的地方，这才慢悠悠的回到了神手谷。在悠闲的回到谷内后不久，韩立就开始准备厉飞雨的所需要的秘药。这个能减轻人疼痛知觉的药并不难配，在山谷中的药园里就能找到所需的所有药材，只是配制的过程有些繁琐，要小心仔细一些。在经过一个下午的忙碌后，韩立配好了足够厉飞雨用一年的成药。不是不能再多配一些，他只是希望厉飞雨以后每年都来取回药，让他不会慢慢遗忘了自己的这份人情。到了傍晚，韩立突然一反常态的坐在了自己屋门前的一把椅子上，抬头望着漆黑的星空，看着皎洁的月亮，在思考着什么。韩立又再怀念家里的亲人了。他离开自己的父母已经四年多了，从他上山以来几乎每天天都在苦苦修炼口诀，根本就无暇惦记家中之事，也就从未下山回去过。只是让人把自己每月领的大部分银子都捎带回家，而他每年也只收到一封老张叔代笔写得父母报平安的书信，信的内容很少，除了告诉他家中的一切都安好外，其他的事情就很少和他提到。只是知道家里的生活比以前好了许多，大哥已经成家立业，二哥也说好了新媳妇，估计明年就能操办喜事，所有这一切变化都是因为自己送回家的银子才改变的，但韩立却从几封信的问候中敏感的觉察到，家里人对待他的口气是越来越客气，甚至客气的有一种像对待陌生人的感觉，这种感觉一开始让韩立心里很害怕，不知如何应对才好。但随着时间的流逝，不知为什么，这种害怕的感觉却很自然地变平淡了下来，而家中亲人的形象在他心目中也逐渐的模糊了。他也只有像今天晚上这样，在触景生情的情况下才会再次怀念起家中的亲人，回想起以前在家中的那种温馨感觉，这种现在很难品尝到的感受，让韩立觉得很舒服很珍贵，他会慢慢的、一点点的品味着这种滋味。韩立把手放到了胸口上，用手指隔着衣服抚mo着装着平安符的小皮袋。以往这时他只要抚mo几下，心灵上就能得到淡淡的满足，但今晚不知怎么回事，抚mo之后心里更骚动不已，久久不能平静下来。韩立现在心里有一种说不出的郁闷感觉，无法控制自己的情绪，身体上下也不对劲，体内的气血开始翻滚不停，修炼出来的古怪能量也蠢蠢欲动。“走火入魔”这个可怕的字眼突然出现在他的脑子里，韩立站了起来，深呼吸了一下，强迫自己冷静下来。现在墨大夫不在，他只有自己处理眼前的危机。自己无缘无故的怎么会走火入魔，韩立还是觉得有点纳闷。虽然现在不是寻根问底的时候，但从根源上入手找到触动走火入魔的起因，才是彻底解决这个麻烦的最可行办法。韩立抬起头，目光往周围寻觅了一番，没有找到什么惹眼的东西\"}END")
# HTTP_END = b"\r\n\r\n"
# CHUNK_END = b"\r\n"
# AUDIO_START = b'{"audio":"'
# AUDIO_END = b'"}'


# def parse_chunked_data(buffer):
#     chunk_end = buffer.find(b"\r\n")
#     data = buffer[:chunk_end]
#     buffer = buffer[chunk_end+len(b"\r\n"):]
#     chunk_end_next = buffer.find(b"\r\n")
#     data =data + buffer[chunk_end_next+len(b"\r\n"):]
#     # print("check_data",data)
#     return data  


# def connect_sse(sseid,token):
#     sock = None
#     try:
#         # 1. 创建 socket
#         sock = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM)
        
#         # 2. 解析主机名和端口
#         host = "web.daomangtu.com"
#         port = 443  # HTTPS 默认端口
        
#         # sockaddr=usocket.getaddrinfo('web.daomangtu.com', 443)[0][-1]
#         # print(sockaddr)
#         sock.connect(('47.119.151.28', 443))  # 注意：参数是 (host, port) 元组
#         sock.settimeout(5)
#         # 4. 启用 SSL/TLS（HTTPS 必须）
#         sock = ussl.wrap_socket(sock, server_hostname="web.daomangtu.com")
#         sse_log.info("SSL/TLS handshake OK")
        
#         # 5. 发送 SSE 请求
#         path = "/jeecgboot/simple/getSimpleMultiModal?sseId=" + sseid + "&token=" + token
        
#         request = (
#             "GET "+path+" HTTP/1.1\r\n"
#             "Host: "+host+"\r\n"
#             "Accept: text/event-stream\r\n"
#             "Connection: keep-alive\r\n"
#             "\r\n"  
#         )
        
#         sse_log.info("Sending SSE request...")
#         sock.write(request)
        
#         # 6. 接收 SSE 数据（持续监听）
#         sse_log.info("Waiting for SSE data...")
#         buffer = b""
#         while True:
#             try:
#                 data = sock.read(1024*8)  # 每次读取 1KB
#                 if not data:
#                     break  # 连接关闭
#                 buffer += data
#                 if HTTP_END in buffer:
#                     _, buffer = buffer.split(HTTP_END, 1)
#                 while True:
#                     # sse_log.info('data:%s' % data)
#                     # 查找音频数据起始位置
#                     start_idx = buffer.find(AUDIO_START)
#                     if start_idx == -1:
#                         break
#                     #print("start_idx:", start_idx)
#                     # 调整起始位置到实际数据开始处
#                     # data_start = start_idx + len(AUDIO_START)
#                     # 查找音频数据结束位置
#                     end_idx = buffer.find(AUDIO_END)
#                     if end_idx == -1:
#                         break
#                     # 提取并解码Base64数据
#                     audio_b64 = buffer[start_idx + len(AUDIO_START):end_idx]
#                     if(CHUNK_END in audio_b64):
#                         audio_b64 = parse_chunked_data(audio_b64)
#                     # print("audio_s:",audio_s)
#                     audio_data = ubinascii.a2b_base64(audio_b64)
#                     aud.playStream(1, audio_data)
#                     # 移除已处理的数据
#                     buffer = buffer[end_idx+len(AUDIO_END):]        
            
#             except Exception as e:
#                 sse_log.error("Error receiving data: %s", e)
#                 break
#         sock.close()
#     except Exception as e:
#         sse_log.error("SSE connection failed: %s", e)
    
#     finally:
#         if sock:
#             sock.close()
#             sse_log.info("Connection closed")


# def pic_http():
#     headers1 = {
#             "x-access-token": TOKEN,  
#             "Content-Type": "application/json"
#         }
#     cam.start(640,480, "pic")
#     utime.sleep_ms(50)
#     #cam.close()
#     try:
#         with open("/usr/pic.jpg", "rb") as f:
#             image_data = f.read()
#             base64_str = ubinascii.b2a_base64(image_data).decode("utf-8").strip()

#     except Exception as e:
#         print("Error reading image:", e)
#         base64_str = ""
#     image_data = "data:image/jpeg;base64,"+base64_str

#     sseid = ""
#     if base64_str and TOKEN:
#         json_str = ujson.dumps({
#             "msgType": "1",
#             "image": image_data
#         })
#         re_voice = request.post("https://web.daomangtu.com/jeecgboot/simple/setData", data=json_str, headers=headers1,sizeof=4096)
#         for i in re_voice.text:
#             sseid += i 
#     else:
#         print("Error: Missing token or image data")
#         print(len(base64_str),len(TOKEN))

#     if sseid:
#         connect_sse(sseid,TOKEN)
#         # headers = {
#         #     "Accept": "text/event-stream"
#         # }
#         # sizeof = 4096
#         # url = "https://web.daomangtu.com/jeecgboot/simple/getSimpleMultiModal?sseId=" + sseid +"&token=" + TOKEN
#         # voice_data = request.get(url, headers=headers, sizeof=40960,stream=True) 
#         # print("OK")
#         # voide_base64 = ""
#         # for i in voice_data.text:
#         #     voide_base64 += i
#         #     if "}" in voide_base64:
#         #         # print("v\n",voide_base64)
#         #         re = ure.match('data:{"audio":"(.+?)"}',voide_base64)  
#         #         q.put(ubinascii.a2b_base64(re.group(1)))
#         #         voide_base64 = voide_base64[(voide_base64.find("}")+3):]
#         #     utime.sleep_ms(10)
#                     # aud.playStream(1,ubinascii.a2b_base64(re.group(1)))

                    
                

#     else:
#         print("Error: Missing sseid")

# def get_tts():
#     headers1 = {
#             "x-access-token": TOKEN,  
#             "Content-Type": "application/json"
#         }
#     cam.start(640,480, "pic")
#     utime.sleep_ms(50)
#     try:
#         with open("/usr/pic.jpg", "rb") as f:
#             image_data = f.read()
#             base64_str = ubinascii.b2a_base64(image_data).decode("utf-8").strip()

#     except Exception as e:
#         print("Error reading image:", e)
#         base64_str = ""
#     image_data = "data:image/jpeg;base64,"+base64_str

#     sseid = ""
#     if base64_str and TOKEN:
#         json_str = ujson.dumps({
#             "msgType": "1",
#             "image": image_data
#         })

#     sseid = ""
#     if base64_str and TOKEN:
#         json_str = ujson.dumps({
#             "msgType": "1",
#             "image": image_data
#         })
#         re_voice = request.post("https://web.daomangtu.com/jeecgboot/simple/setData", data=json_str, headers=headers1,sizeof=4096)
#         for i in re_voice.text:
#             sseid += i 
#     else:
#         print("Error: Missing token or image data")

#     re = request.get("https://api.vvhan.com/api/ian/rand?type=json",sizeof=4096)
#     t1_str = re.json()
#     print("OK")
#     tts.play(1, 0, 2, t1_str["data"]["content"])


# key1 = Pin(Pin.GPIO13,Pin.IN,Pin.PULL_PU)
# Key2 = Pin(Pin.GPIO12,Pin.IN,Pin.PULL_PU)

# def key():
#     while True:
#         if key1.read() == 0:
#             get_tts()
#         if Key2.read() == 0:
#             pic_http()
#         utime.sleep_ms(200)

# def play_voice():
#     i = 0
#     voice_data = ""
#     while True:
#         if q.size() > 5:
#             while q.size()!=0:
#                 aud.playStream(1,q.get())
#         utime.sleep_ms(500)

# if __name__ == '__main__':
#     _thread.start_new_thread(key,())
#     _thread.start_new_thread(play_voice,())


#cam.start(480, 640, "123")

# play = audio.Audio(0)
# tts = audio.TTS(0)
# play.setVolume(9)
# tts.setSpeed(9)
# tts.play(1, 0, 2, '1234568')
# tts.play(1, 0, 2, '二愣子睁大着双眼，直直望着茅草和烂泥糊成的黑屋顶，身上盖着的旧棉被，已呈深黄色，看不出原来的本来面目，还若有若无的散发着淡淡的霉味。\
#          在他身边紧挨着的另一人，是二哥韩铸，酣睡的十分香甜，从他身上不时传来轻重不一的阵阵打呼声。')
# print("mp3播放测试")
# play = audio.Audio(0)
# print(play.set_pa(22,2))

# print(play.play(2,1,"1.mp3"))

# callback使用示例
# from usr.WLAN import ESP8266
# from machine import UART

# def cb(args):
#     content = args
#     print('wifi content:{}'.format(content))

# ESP8266 = ESP8266(UART.UART1, ESP8266.STA, cb)
# print(ESP8266.status())
